#!/usr/bin/bash


authselect check &> /dev/null && auCheck=0

if [[ $auCheck == "0" ]] ; then
    customProfile=$(authselect current | awk 'NR == 1 {print $3}' | grep custom/)
    currProfile=$(authselect current | awk 'NR == 1 {print $3}')
    createP="user-profile"

    # 判断是否已有用户自定义规则集，如有则跳过创建步骤，改为直接追加已有的规则集
    if [[ -z $customProfile ]]; then
        authselect create-profile $createP -b $currProfile
        authselect select custom/$createP
        authselect apply-changes
    fi
fi

[[ $auCheck == "0" ]] && customProfile=$(authselect current | awk 'NR == 1 {print $3}' | grep custom/) || customProfile=""
# 判断是否有自定义规则集，如没有或创建失败，则直接对最终文件(/etc/pam.d/password-auth,/etc/pam.d/system-auth)进行修改
for FN in system-auth password-auth; do
    [[ -n $customProfile ]] && PTF=/etc/authselect/$customProfile/$FN || PTF=/etc/pam.d/$FN
    [[ -z $(grep -E '^\s*password\s+requisite\s+pam_pwquality.so.*$' $PTF) ]] && ln=$(grep -En -m1 '^\s*password\s+' $PTF | cut -d: -f1) && sed -i "${ln}i\password    requisite    pam_pwquality.so " $PTF
    [[ -z $(grep -E '^\s*password\s+requisite\s+pam_pwquality.so\s+.*enforce-for-root\s*.*$' $PTF) ]] && sed -ri 's/^\s*(password\s+requisite\s+pam_pwquality.so\s+)(.*)$/\1\2 enforce-for-root/' $PTF
    [[ -n $(grep -E '^\s*password\s+requisite\s+pam_pwquality.so\s+.*\s+retry=\S+\s*.*$' $PTF) ]] && sed -ri '/pwquality/s/retry=\S+/retry=3/' $PTF || sed -ri 's/^\s*(password\s+requisite\s+pam_pwquality.so\s+)(.*)$/\1\2 retry=3/' $PTF
done
[[ $auCheck == "0" ]] && authselect apply-changes &> /dev/null

minlenValue=$(grep -P "^\s*minlen\s*=.*" /etc/security/pwquality.conf | cut -d= -f2 | tr -d '[:space:]')
if [[ -z $minlenValue ]] ; then
    echo "minlen=14" >> /etc/security/pwquality.conf
elif [[ $minlenValue =~ ^[0-9]+$ ]] && [[ $minlenValue -lt 14 ]] ; then
    sed -ri "s/^(\s*)minlen\s*=\s*\S+(\s*#.*)?\s*$/\minlen=14\2/" /etc/security/pwquality.conf
else
    sed -ri "s/^(\s*)minlen\s*=\s*\S+(\s*#.*)?\s*$/\minlen=14\2/" /etc/security/pwquality.conf
fi

# minclass 与 credit 效果一致，任选其一即可，这里只修改minclass参数
grep -Eq "^(\s*)minclass\s*=\s*\S+(\s*#.*)?\s*$" /etc/security/pwquality.conf && sed -ri "s/^(\s*)minclass\s*=\s*\S+(\s*#.*)?\s*$/\minclass=4\2/" /etc/security/pwquality.conf || echo "minclass=4" >> /etc/security/pwquality.conf
